package com.GainLoop.Adapters;

import java.util.Hashtable;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;

import com.GainLoop.Api.ApiResponseArray;
import com.GainLoop.Api.ApiResponseObject;
import com.GainLoop.Api.Gains;
import com.GainLoop.Api.Users;
import com.GainLoop.Api.Entity.Gain;
import com.GainLoop.Api.Entity.User;
import com.GainLoop.Data.Registry;
import com.GainLoop.Utils.AppUtils;
import com.GainLoop.Utils.LayoutUtils;
import com.GainLoop.Utils.ResourceUtils;

import android.app.Activity;
import android.util.Log;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class OffersListAdapter extends BaseAdapter {

	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// data members
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	/** holds all the weather data */
	private Hashtable<Long, Gain> _data = new Hashtable<Long, Gain>();

	/** holds the currently selected position */
	private int _selectedIndex;
	private Activity _context;

	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// constructor
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

	/**
	 * create the model-view object that will control the listview
	 *
	 * @param context  activity that creates this thing
	 * @param listview bind to this listview
	 */
	 public OffersListAdapter(final Activity context, ListView listview) {

	  // save the activity/context ref
	  _context = context;

	  // bind this model (and cell renderer) to the listview
	  listview.setAdapter(this);

	//load data into the model
	 Gains gains = new Gains();
	 ApiResponseObject<Gain> gain=null;
	 ApiResponseArray<Gain> gainsArr=null;
	 try {
		gainsArr= gains.getOffers(1,5);
		gain=gains.getById(3);
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JSONRPCException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	  //User user=Registry.GetUser();
	  Log.v("test", "array return code: "+gainsArr.getReturnCode());
	 //_data.put(user.getId(), user);
	  if (gainsArr!=null&&gainsArr.getData().size()>0){
		  _data.put((long)gainsArr.getData().get(0).getId(), gainsArr.getData().get(0));
		  //_data.put((long)gainsArr.getData().get(1).getId(), gainsArr.getData().get(1));
		  Log.v("test","getOffers data inserted");
	  }
	  if (gain!=null){
		 _data.put((long)gain.getData().getId(), gain.getData());
		  Log.v("test","getById data inserted");
	  }
	
	  //_data.put((long)1, new User());
	  Log.i(getClass().getSimpleName(), "loading data set, creating list model, and binding to listview");

	}

	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	// implement ListAdapter - how big is the underlying list data, and how to iterate it...
	// the underlying data is a Map of Maps, so this really reflects the keyset of the enclosing Map...
	//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
	/** returns all the items in the {@link #_data} table */
	public int getCount() {
	  return _data.size();
	}

	/** returns the key for the table, not the value (which is another table) */
	public Object getItem(int i) {
	  Object retval = _data.keySet().toArray()[i];
	  Log.i(getClass().getSimpleName(), "getItem(" + i + ") = " + retval);
	  return retval;
	}

	/** returns the unique id for the given index, which is just the index */
	public long getItemId(int i) {
	  return i;
	}
	/**
	 * called when item in listview is selected... fires a model changed event...
	 *
	 * @param index index of item selected in listview. if -1 then it's unselected.
	 */
	public void setSelected(int index) {
		Log.i(getClass().getSimpleName(),
		        "index selected =" + index);
	  if (index == -1) {
	    // unselected
	  }
	  else {
	    
	  }

	  _selectedIndex = index;

	  // notify the model that the data has changed, need to update the view
	  notifyDataSetChanged();

	  Log.i(getClass().getSimpleName(),
	        "updating _selectionIndex with index and firing model-change-event: index=" + index);

	}

	@Override public View getView(int index,
	                              View cellRenderer,
	                              ViewGroup parent)
	{

	  CellRendererView cellRendererView = null;

	  if (cellRenderer == null) {
	    // create the cell renderer
	    Log.i(getClass().getSimpleName(), "creating a CellRendererView object");
	    cellRendererView = new CellRendererView();
	  }
	  else {
	    cellRendererView = (CellRendererView) cellRenderer;
	  }

	  // update the cell renderer, and handle selection state
	  cellRendererView.display(index,
	                           _selectedIndex == index);

	  return cellRendererView;

	}
	
	/** this class is responsible for rendering the data in the model, given the selection state */
	private class CellRendererView extends TableLayout {

	  // ui stuff
	  private TextView _lblName;
	  private ImageView _lblIcon;
	  private TextView _lblDescription;

	  public CellRendererView() {

	    super(_context);

	    _createUI();

	  }

	  /** create the ui components */
	  private void _createUI() {

	    // make the 2nd col growable/wrappable
	    setColumnShrinkable(1, true);
	    setColumnStretchable(1, true);

	    // set the padding
	    setPadding(10, 10, 10, 10);

	    // single row that holds icon/flag & name
	    TableRow row = new TableRow(_context);
	    LayoutUtils.Layout.WidthFill_HeightWrap.applyTableLayoutParams(row);

	    // fill the first row with: icon/flag, name
	    {
	      _lblName = new TextView(_context);
	      LayoutUtils.Layout.WidthWrap_HeightWrap.applyTableRowParams(_lblName);
	      _lblName.setPadding(10, 10, 10, 10);

	      _lblIcon = AppUtils.createImageView(_context, -1, -1, -1);
	      LayoutUtils.Layout.WidthWrap_HeightWrap.applyTableRowParams(_lblIcon);
	      _lblIcon.setPadding(10, 10, 10, 10);

	      row.addView(_lblIcon);
	      row.addView(_lblName);
	    }

	    // create the 2nd row with: description
	    {
	      _lblDescription = new TextView(_context);
	      LayoutUtils.Layout.WidthFill_HeightWrap.applyTableLayoutParams(_lblDescription);
	      _lblDescription.setPadding(10, 10, 10, 10);
	    }

	    // add the rows to the table
	    {
	      addView(row);
	      addView(_lblDescription);
	    }

	    Log.i(getClass().getSimpleName(), "CellRendererView created");

	  }

	  /** update the views with the data corresponding to selection index */
	  public void display(int index, boolean selected) {

	    Long id = (Long)getItem(index);
	    Gain gain = _data.get(id);

	    Log.i(getClass().getSimpleName(), "row[" + index + "] = " + gain.toString());

	    
	    
	   // int iconId = ResourceUtils.getResourceIdForDrawable(_context, "com.developerlife", "w" + icon);

	    String desc = gain.getDescription();

	    _lblName.setText(desc );
	    //_lblIcon.setImageResource(iconId);
	    _lblDescription.setText("id: "+id);

	    Log.i(getClass().getSimpleName(), "rendering index:" + index);

	    if (selected) {
	      _lblDescription.setVisibility(View.VISIBLE);
	      Log.i(getClass().getSimpleName(), "hiding descripton for index:" + index);
	    }
	    else {
	      _lblDescription.setVisibility(View.GONE);
	      Log.i(getClass().getSimpleName(), "showing description for index:" + index);
	    }

	  }

	}
}
